package service

import (
	"ginblog/enum"
	"ginblog/model"
)

type CategoryService struct {
}

type CategorySerInterface interface {
	CheckCategory(name string) enum.Code
	CreateCategory(data *model.Category) enum.Code
	GetCategorys(pageSize, pageNum int) ([]model.Category, int64)
	GetCategoryById(userId int) (category model.Category, code enum.Code)
	EditCategory(id int, data *model.Category) enum.Code
	DeleteCategory(id int) enum.Code
}

// CheckCategory 查询分类是否被使用
func (cate *CategoryService) CheckCategory(name string) enum.Code {
	var data model.Category
	db.Select("id").Where("name = ?", name).First(&data)
	if data.ID > 0 {
		return enum.ErrorCatenameUsed
	}

	return enum.SUCCESS
}

// CreateCategory 添加分类
func (cate *CategoryService) CreateCategory(data *model.Category) enum.Code {
	err := db.Create(data).Error
	if err != nil {
		return enum.ERROR
	}

	return enum.SUCCESS
}

// GetCategorys 查询分类列表
func (cate *CategoryService) GetCategorys(pageSize, pageNum int) ([]model.Category, int64) {
	var categorys []model.Category
	var count int64 = 0
	// 单独计数
	db.Model(&categorys).Count(&count)
	err := db.Limit(pageSize).Offset((pageNum - 1) * pageSize).Find(&categorys).Error
	if err != nil {
		// 没有数据
		return nil, 0
	}

	return categorys, count
}

// GetCategoryById 根据id查询分类
func (cate *CategoryService) GetCategoryById(userId int) (category model.Category, code enum.Code) {
	var categorys model.Category
	err := db.First(&categorys, userId).Error
	if err != nil {
		return categorys, enum.ERROR
	}

	return categorys, enum.SUCCESS
}

// EditCategory 编辑分类
func (cate *CategoryService) EditCategory(id int, data *model.Category) enum.Code {

	err := db.Model(&model.Category{}).Where("id = ?", id).Update("name", data.Name).Error
	if err != nil {
		return enum.ERROR
	}
	return enum.SUCCESS
}

// DeleteCategory 删除分类
func (cate *CategoryService) DeleteCategory(id int) enum.Code {
	err := db.Delete(&model.Category{}, id).Error
	if err != nil {
		return enum.ERROR
	}
	return enum.SUCCESS
}
